package queue

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	"github.com/hibiken/asynq"
)

type OrderProcessor struct {
	ctx context.Context
}

// NewOrderProcessor 实例化processor
func NewOrderProcessor(ctx context.Context) *OrderProcessor {
	return &OrderProcessor{
		ctx: ctx,
	}
}

// SendTask 发送任务
func (s *OrderProcessor) SendTask(params Payload) (*asynq.Task, error) {
	payload, err := json.Marshal(params)
	if err != nil {
		return nil, err
	}

	return asynq.NewTask(Order, payload, asynq.MaxRetry(5), asynq.Timeout(5*time.Minute), asynq.ProcessIn(params.ProcessIn)), nil
}

// ProcessTask 处理任务
func (s *OrderProcessor) ProcessTask(ctx context.Context, t *asynq.Task) error {
	var p Payload
	if err := json.Unmarshal(t.Payload(), &p); err != nil {
		return fmt.Errorf("json.Unmarshal failed: %v: %w", err, asynq.SkipRetry)
	}
	params := p.Params.(map[string]interface{})
	i := params["user_id"]
	fmt.Printf("ctx : %# v\n", params)
	fmt.Printf("ctx : %# v\n", i)

	return nil
}
